package edu.hncj.seckill.service.impl;


import edu.hncj.seckill.service.SmsSerive;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author anorak
 */
@Service
public class SmsServiceImpl implements SmsSerive {

    @Override
    public String sendSms(String telPhone, String template) throws Exception {
        return sendInfo(telPhone, template,true);
    }

    @Override
    public String checkCode(String telPhone, String code) throws Exception {
        return sendInfo(telPhone, code,false);
    }

    /**
     * 发送验证短信或验证
     * @param telPhone 手机号
     * @param arg 参数
     * @param flag 标记位
     * @return 法诺结果
     */
    private String sendInfo(String telPhone, String arg,Boolean flag) throws IOException {
        // 创建http客户端
        HttpClient httpClient = new DefaultHttpClient();
        // 创建HttpPost请求
        String url = "";
        JSONObject param = new JSONObject();
        if (flag){
            url = "https://api2.bmob.cn/1/requestSmsCode";
            param.put("mobilePhoneNumber",telPhone);
            param.put("template",arg);
        }else {
            url = "https://api2.bmob.cn/1/verifySmsCode/" + arg;
            param.put("mobilePhoneNumber",telPhone);
        }
        HttpPost post = new HttpPost(url);
        post.setHeader("X-Bmob-Application-Id","493409837f1cf2f89df662d556208d7f");
        post.setHeader("X-Bmob-REST-API-Key","f296c55422b3c1d97569c29a3a17f6ac");
        post.setHeader("Content-Type", "application/json");
        // 设置参数
        post.setEntity(new StringEntity(param.toString(), "UTF-8"));
        // 执行post请求操作，并拿到结果
        HttpResponse httpResponse = httpClient.execute(post);
        // 获取结果实体
        HttpEntity entity = httpResponse.getEntity();
        // 设置返回String
        String body = "";
        // 对获取的数据处理
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, HTTP.UTF_8);
        }
        // 关闭Http客户端
        httpClient.getConnectionManager().shutdown();
        return body;
    }

}
